package library.and.xps.com.step.util;

import io.realm.Realm;
import library.and.xps.com.step.m.model.BaseResponce;
import library.and.xps.com.step.m.model.CreateTeamResponce;
import library.and.xps.com.step.m.model.Team;
import library.and.xps.com.step.m.model.User;

public class TeamHelper {
    private static final TeamHelper ourInstance = new TeamHelper();
    private Realm realm;

    public static TeamHelper getIns() {
        return ourInstance;
    }

    private TeamHelper() {
        realm = Realm.getDefaultInstance();
    }

    /**
     * @param user 本地用户
     * @param res  服务器返回
     *             插入已加入团队如数据库
     */
    public void insertTeam(User user, BaseResponce res) {
        Team team = new Team();
        CreateTeamResponce createTeamResponce = (CreateTeamResponce) res;

        if (HttpResponsHelper.SuccessResponce(createTeamResponce)) {
            realm.beginTransaction();
            team.setAddress(createTeamResponce.getObj().getAddress());
            team.setCreatenickname(createTeamResponce.getObj().getCreatenickname());
            team.setCreater(createTeamResponce.getObj().getCreater() + "");
            team.setCreatetime(createTeamResponce.getObj().getCreatetime() + "");
            team.setTname(createTeamResponce.getObj().getTname());
            team.setEnterprise(createTeamResponce.getObj().getEnterprise());
            team.setEnterpriseid(createTeamResponce.getObj().getEnterpriseid() + "");
            team.setDescription(createTeamResponce.getObj().getDescription());
            team.setTeamId(createTeamResponce.getObj().getTeamid() + "");
            team.setType(createTeamResponce.getObj().getType() + "");
            team.setMarker(createTeamResponce.getObj().getMark());
            team.setEmail(createTeamResponce.getObj().getEmail());
            team.setRole(createTeamResponce.getObj().getRole());
            user.getTeams().clear();
            user.getTeams().add(team);
            realm.commitTransaction();
        }
    }

    public boolean hasTeam() {
        User user = realm.where(User.class).findFirst();
        if (user != null && null!=user.getTeams()&&user.getTeams().size()>0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回一个只读的Team
     * */
    public Team getCurT() {
        User user = realm.where(User.class).findFirst();
        if (user != null && null!=user.getTeams()&&user.getTeams().size()>0) {
            return user.getTeams().get(0);
        } else {
            return null;
        }
    }


    /**
     * 返回一个只读的Team
     * */
    public String getTid() {
        return getCurT().getTId();
    }

}
